using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesClaimsPendingForApprovalDetail : System.Web.UI.Page
{
    #region Variables
    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected GonzalesClaimHeader ResultObj = null;
    protected readonly int TotalColumns = 20;
    protected MasterBaseCollection ExchangeRate = new MasterBaseCollection();
    protected int IsFirstTime = 0;
    protected decimal TotalPersonalExpenses = 0;

    #region ClaimHavingCreditCard
    protected bool ClaimHavingCreditCard
    {
        get
        {
            return (bool)ViewState["ClaimHavingCreditCard"];
        }

        set
        {
            ViewState["ClaimHavingCreditCard"] = value;
        }
    }
    #endregion

    #region ClaimInternalID
    protected string ClaimInternalID
    {
        get
        {
            return ViewState["ClaimInternalID"].ToString();
        }

        set
        {
            ViewState["ClaimInternalID"] = value;
        }
    }
    #endregion

    #region Common Variables for Language Translation

    #region ItemExpenseDetail
    protected string ItemExpenseDetail
    {
        get
        {
            return ViewState["ItemExpenseDetail"].ToString();
        }

        set
        {
            ViewState["ItemExpenseDetail"] = value;
        }
    }
    #endregion

    #region ItemRemarks
    protected string ItemRemarks
    {
        get
        {
            return ViewState["ItemRemarks"].ToString();
        }

        set
        {
            ViewState["ItemRemarks"] = value;
        }
    }
    #endregion

    #region ItemDate
    protected string ItemDate
    {
        get
        {
            return ViewState["ItemDate"].ToString();
        }

        set
        {
            ViewState["ItemDate"] = value;
        }
    }
    #endregion

    #region ItemDateEnd
    protected string ItemDateEnd
    {
        get
        {
            return ViewState["ItemDateEnd"].ToString();
        }

        set
        {
            ViewState["ItemDateEnd"] = value;
        }
    }
    #endregion

    #region ItemLocation
    protected string ItemLocation
    {
        get
        {
            return ViewState["ItemLocation"].ToString();
        }

        set
        {
            ViewState["ItemLocation"] = value;
        }
    }
    #endregion

    #region ItemClaimed
    protected string ItemClaimed
    {
        get
        {
            return ViewState["ItemClaimed"].ToString();
        }

        set
        {
            ViewState["ItemClaimed"] = value;
        }
    }
    #endregion

    #region ItemTax
    protected string ItemTax
    {
        get
        {
            return ViewState["ItemTax"].ToString();
        }

        set
        {
            ViewState["ItemTax"] = value;
        }
    }
    #endregion

    #region ItemExCurrency
    protected string ItemExCurrency
    {
        get
        {
            return ViewState["ItemExCurrency"].ToString();
        }

        set
        {
            ViewState["ItemExCurrency"] = value;
        }
    }
    #endregion

    #region ItemExRate
    protected string ItemExRate
    {
        get
        {
            return ViewState["ItemExRate"].ToString();
        }

        set
        {
            ViewState["ItemExRate"] = value;
        }
    }
    #endregion

    #region ItemLocalAmount
    protected string ItemLocalAmount
    {
        get
        {
            return ViewState["ItemLocalAmount"].ToString();
        }

        set
        {
            ViewState["ItemLocalAmount"] = value;
        }
    }
    #endregion

    #region ItemTooltipsReceipt
    protected string ItemTooltipsReceipt
    {
        get
        {
            return ViewState["ItemTooltipsReceipt"].ToString();
        }

        set
        {
            ViewState["ItemTooltipsReceipt"] = value;
        }
    }
    #endregion

    #region ItemProjectID
    protected string ItemProjectID
    {
        get
        {
            return ViewState["ItemProjectID"].ToString();
        }

        set
        {
            ViewState["ItemProjectID"] = value;
        }
    }
    #endregion

    #region ItemChargeToProfitCenter
    protected string ItemChargeToProfitCenter
    {
        get
        {
            return ViewState["ItemChargeToProfitCenter"].ToString();
        }

        set
        {
            ViewState["ItemChargeToProfitCenter"] = value;
        }
    }
    #endregion

    #region ItemChargeToEmployeeID
    protected string ItemChargeToEmployeeID
    {
        get
        {
            return ViewState["ItemChargeToEmployeeID"].ToString();
        }

        set
        {
            ViewState["ItemChargeToEmployeeID"] = value;
        }
    }
    #endregion

    #region ItemDetail
    protected string ItemDetail
    {
        get
        {
            return ViewState["ItemDetail"].ToString();
        }

        set
        {
            ViewState["ItemDetail"] = value;
        }
    }
    #endregion

    #region ItemApprove
    protected string ItemApprove
    {
        get
        {
            return ViewState["ItemApprove"].ToString();
        }

        set
        {
            ViewState["ItemApprove"] = value;
        }
    }
    #endregion

    #region AltNoDetail
    protected string AltNoDetail
    {
        get
        {
            return ViewState["AltNoDetail"].ToString();
        }

        set
        {
            ViewState["AltNoDetail"] = value;
        }
    }
    #endregion

    #region ItemTooltipApproverRemarks
    protected string ItemTooltipApproverRemarks
    {
        get
        {
            return ViewState["ItemTooptipApproverRemarks"].ToString();
        }

        set
        {
            ViewState["ItemTooptipApproverRemarks"] = value;
        }
    }
    #endregion

    #region UnexpectedMesage
    protected string UnexpectedMesage
    {
        get
        {
            return ViewState["UnexpectedMesage"].ToString();
        }

        set
        {
            ViewState["UnexpectedMesage"] = value;
        }
    }
    #endregion

    #region ReceiptNo
    protected string ReceiptNo
    {
        get
        {
            return ViewState["ReceiptNo"].ToString();
        }

        set
        {
            ViewState["ReceiptNo"] = value;
        }
    }
    #endregion

    #region CreditCardDetails
    protected string CreditCardDetails
    {
        get
        {
            return ViewState["CreditCardDetails"].ToString();
        }

        set
        {
            ViewState["CreditCardDetails"] = value;
        }
    }
    #endregion

    #region ApproveWarning2
    protected string ApproveWarning2
    {
        get
        {
            return ViewState["ApproveWarning2"].ToString();
        }

        set
        {
            ViewState["ApproveWarning2"] = value;
        }
    }
    #endregion

    #region ApproveWarning
    protected string ApproveWarning
    {
        get
        {
            return ViewState["ApproveWarning"].ToString();
        }

        set
        {
            ViewState["ApproveWarning"] = value;
        }
    }
    #endregion

    #region ItemRejectMessage
    protected string ItemRejectMessage
    {
        get
        {
            return ViewState["ItemRejectMessage"].ToString();
        }

        set
        {
            ViewState["ItemRejectMessage"] = value;
        }
    }
    #endregion

    #region ItemRejectWarning
    protected string ItemRejectWarning
    {
        get
        {
            return ViewState["ItemRejectWarning"].ToString();
        }

        set
        {
            ViewState["ItemRejectWarning"] = value;
        }
    }
    #endregion

    #region ItemRejectAlert
    protected string ItemRejectAlert
    {
        get
        {
            return ViewState["ItemRejectAlert"].ToString();
        }

        set
        {
            ViewState["ItemRejectAlert"] = value;
        }
    }
    #endregion

    #endregion

    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();
        this.Table_MessageBox.Visible = false;

        if (!IsPostBack)
        {
            #region Request.QueryString["id"]

            if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36)
            {
                this.ClaimInternalID = Request.QueryString["id"];
            }
            else
            {
                Response.Redirect(GonzalesErrorPageRedirect.PageFlowError);
            }

            #endregion

            this.ClaimHavingCreditCard = false; // default

            this.SwitchLanguage();
            this.PageComponentSetup();

            this.LoadData();

            if (this.ResultObj != null)
            {
                this.BuiltTable();

                for (int x = 0; x < this.ResultObj.ClaimDetails.Count; x++)
                {
                    GonzalesClaimItem CurrentClaimItem = (GonzalesClaimItem)this.ResultObj.ClaimDetails[x];
                    this.ClaimHavingCreditCard = (CurrentClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard) ? true : this.ClaimHavingCreditCard;

                    this.BuiltRow((x + 1), CurrentClaimItem);
                }

                this.FillInData();

                this.PolicyEnvironmentSetup();  // start to do policy setup

                // hide the credit card and personal
                if (!this.ClaimHavingCreditCard)
                {
                    for (int x = 0; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
                    {
                        this.Table_ClaimDetailGrid.Rows[x].Cells[2].Visible = this.Table_ClaimDetailGrid.Rows[x].Cells[3].Visible = false;
                    }
                }
            }
        }
        else
        {
            // if this is a postback
            this.LoadData();

            // built up everything first
            this.BuiltTable();

            for (int x = 0; x < this.ResultObj.ClaimDetails.Count; x++)
            {
                GonzalesClaimItem CurrentClaimItem = (GonzalesClaimItem)this.ResultObj.ClaimDetails[x];
                this.BuiltRow((x+1), CurrentClaimItem);
            }

            IsFirstTime = 1;
        }

        this.LabelValue_TotalPersonalExpenses.Text = TotalPersonalExpenses.ToString(GonzalesGeneralVariables.CurrencyFormat);
        this.Label_TotalLocalAmount.Text = (this.ResultObj.TotalClaimedAmount - TotalPersonalExpenses).ToString(GonzalesGeneralVariables.CurrencyFormat);
        this.ShadowUserPolicy();
        this.GeneralVariable();
    }
    #endregion

    #region Button_Approve_Click
    protected void Button_Approve_Click(object sender, EventArgs e)
    {
        if (this.DataValidate("approved"))
        {
            if (this.DataCollect())
            {
                // check what is the user approving structure
                SystemUser Claimant = null;
                using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                {
                    Claimant = CurUserManager.GetUserByInternalID(this.ResultObj.ClaimedBy.InternalID);

                    if (Claimant == null)
                    {
                        string LogID = SwissArmy.UniqueID();
                        this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.Button_Approve_Click] : Failed at CurUserManager.GetUserByInternalID('" + this.ResultObj.ClaimedBy.InternalID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                        this.ShowErrorMessage(this.UnexpectedMesage + LogID);
                    }
                    else
                    {
                        bool EndApproverRoute = false;                        

                        if (Claimant.AppRoute == ApprovingRoute.Exception)
                        {
                            SystemUser NextApprover = CurUserManager.GetNextApproverForExceptionCase(Claimant.InternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, ref EndApproverRoute);

                            if (EndApproverRoute)
                            {
                                // if this is the last people in the Exceptional setting
                                // no need to continue, just set to approve

                                this.ResultObj.ApprovedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                                this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.Approved;
                                this.ResultObj.ApprovedOn = DateTime.Now;
                            }
                            else
                            {
                                // if this is not the last people, check the limit first to see if need to continur

                                MasterBaseCollection CurrencyCollection = null;
                                decimal ApprovingLimitInLocal = 0;

                                // diff currency, need to convert
                                using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
                                {
                                    CurrencyCollection = CurCurrencyManager.GetLatestExchangeRate(this.ResultObj.LocalCurrency);
                                }

                                for (int x = 0; x < CurrencyCollection.Count; x++)
                                {
                                    Currency CurCurrency = (Currency)CurrencyCollection[x];

                                    if (CurCurrency.InternalID.CompareTo(this.CurrentPrivateSession.CurrentLoggedOnUser.ApprovingCurrency.InternalID) == 0)
                                    {
                                        ApprovingLimitInLocal = this.CurrentPrivateSession.CurrentLoggedOnUser.ApprovingLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());
                                        break;
                                    }
                                }

                                // check if exceed the limit
                                if (this.ResultObj.TotalClaimedAmount > ApprovingLimitInLocal)
                                {
                                    this.ResultObj.NextApprover = NextApprover;
                                    this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.Escalated; // escalated, mean approve, and go to next level 
                                }
                                else
                                {
                                    this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.Approved;
                                    this.ResultObj.ApprovedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                                    this.ResultObj.ApprovedOn = DateTime.Now;
                                }                                                                                                                              
                            }

                        }
                        else if (Claimant.AppRoute == ApprovingRoute.MultiLevel)
                        {
                            // check if over here having checkpoint
                            // if having checkpoint, everything stop here
                            
                            if (this.CurrentPrivateSession.CurrentLoggedOnUser.ApprovalCheckPoint)
                            {
                                EndApproverRoute = true;
                            }

                            if (EndApproverRoute)
                            {
                                this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.Approved;
                                this.ResultObj.ApprovedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                                this.ResultObj.ApprovedOn = DateTime.Now;                                
                            }
                            else
                            {
                                MasterBaseCollection CurrencyCollection = null;
                                decimal ApprovingLimitInLocal = 0;

                                // diff currency, need to convert
                                using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
                                {
                                    CurrencyCollection = CurCurrencyManager.GetLatestExchangeRate(this.ResultObj.LocalCurrency);
                                }

                                for (int x = 0; x < CurrencyCollection.Count; x++)
                                {
                                    Currency CurCurrency = (Currency)CurrencyCollection[x];

                                    if (CurCurrency.InternalID.CompareTo(this.CurrentPrivateSession.CurrentLoggedOnUser.ApprovingCurrency.InternalID) == 0)
                                    {
                                        ApprovingLimitInLocal = this.CurrentPrivateSession.CurrentLoggedOnUser.ApprovingLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());                                        
                                        break;
                                    }
                                }

                                // check if exceed the limit
                                if (this.ResultObj.TotalClaimedAmount > ApprovingLimitInLocal)
                                {
                                    this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.Escalated;
                                    this.ResultObj.NextApprover = this.CurrentPrivateSession.CurrentLoggedOnUser.PersonnelReportTo;
                                }
                                else
                                {
                                    this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.Approved;
                                    this.ResultObj.ApprovedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                                    this.ResultObj.ApprovedOn = DateTime.Now;                                
                                }
                            }

                        }
                        else if (Claimant.AppRoute == ApprovingRoute.Normal)
                        {
                            EndApproverRoute = true;

                            this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.Approved;
                            this.ResultObj.ApprovedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                            this.ResultObj.ApprovedOn = DateTime.Now;
                        }

                        #region Get Authorizer if needed
                        if (this.ResultObj.Status == GonzalesClaimHeader.TypeOfClaimStatus.Approved)
                        {
                            // get authorizer if needed
                            // if the claimant is free from authorizer, then skip this
                            if (Claimant.NoAuthorizer)
                            {
                                // no authorizer required, so is auto
                                // now, it is ready for finance verification
                                this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.PendingForFinanceVerification;                                
                            }
                            else
                            {
                                bool AuthorizedNeeded = false; // default, assume no need to
                                Authoriser NextAuthorizer = this.GetAuthorizer(ref AuthorizedNeeded);
                                this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.PendingForAuthorize;

                                if (AuthorizedNeeded)
                                {
                                    // authorization required
                                    this.ResultObj.NextAuthorizer = NextAuthorizer;
                                }
                                else
                                {
                                    // no authorizer required, so is auto
                                    // now, it is ready for finance verification
                                    this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.PendingForFinanceVerification;
                                }
                            }
                        }
                        #endregion

                        // status update                    
                        this.ResultObj.LastUpdatedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                        this.ResultObj.LastUpdatedOn = DateTime.Now;

                        if (this.DataSave())
                        {
                            //Added by Agnes - Hard coded for Brian.King to disabled the Email.
                            if (Claimant.EmailID.ToLower().CompareTo("brian.king") != 0)
                            {
                                #region Send email

                                if (GonzalesGeneralVariables.EmailActive)
                                {
                                    string MailContent = "", MailTitle = "";

                                    #region If the claim already approved by last approver

                                    if (this.ResultObj.Status == GonzalesClaimHeader.TypeOfClaimStatus.PendingForFinanceVerification || this.ResultObj.Status == GonzalesClaimHeader.TypeOfClaimStatus.PendingForAuthorize)
                                    {
                                        using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimApproved, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                                        {
                                            MailContent = CurMailGenerator.GenerateApprovedClaimForClaimant(
                                                Claimant.DisplayName,
                                                Claimant.EmployeeID,
                                                Claimant.EmailID,
                                                Claimant.FromCompany.CompanyName,
                                                this.ResultObj.ClaimID,
                                                this.ResultObj.Reasons,
                                                this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                                                this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName,
                                                GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.APPROVED_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + Claimant.EmailID);

                                            MailTitle = CurMailGenerator.MailTitle;
                                        }

                                        if (MailContent != null && MailContent.Length > 0 && MailTitle.Length > 0)
                                        {
                                            using (EmailFactory CurEmailFactory = new EmailFactory(
                                                Claimant.DisplayName,
                                                Claimant.Email,
                                                MailTitle,
                                                MailContent))
                                            {
                                                if (!CurEmailFactory.SendNow())
                                                {
                                                    string LogID = SwissArmy.UniqueID();
                                                    this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.Button_Approve_Click] : Failed at CurEmailFactory.SendNow() : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                                }
                                            }
                                        }
                                    }

                                    #endregion

                                    #region If the claim need to go to authorizer

                                    if (this.ResultObj.Status == GonzalesClaimHeader.TypeOfClaimStatus.PendingForAuthorize)
                                    {
                                        SystemUser Receiver = CurUserManager.GetUserByInternalID(this.ResultObj.NextAuthorizer.InternalID);

                                        if (Receiver != null && Receiver.EmailID.ToLower().CompareTo("brian.king") != 0)
                                        {
                                            using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimPendingAuthorize, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                                            {
                                                MailContent = CurMailGenerator.GeneratePendingForAuthorizerClaimForAuthorizer(
                                                    Claimant.DisplayName,
                                                    Claimant.EmployeeID,
                                                    Claimant.EmailID,
                                                    Claimant.FromCompany.CompanyName,
                                                    this.ResultObj.ClaimID,
                                                    this.ResultObj.Reasons,
                                                    this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                                                    this.ResultObj.SubmittedOn.ToLongDateString(),
                                                    GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.PENDINGAUTH_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + Receiver.EmailID);

                                                MailTitle = CurMailGenerator.MailTitle;
                                            }

                                            if (MailContent != null && MailContent.Length > 0 && MailTitle.Length > 0)
                                            {
                                                using (EmailFactory CurEmailFactory = new EmailFactory(
                                                    Receiver.DisplayName,
                                                    Receiver.Email,
                                                    MailTitle,
                                                    MailContent))
                                                {
                                                    if (!CurEmailFactory.SendNow())
                                                    {
                                                        string LogID = SwissArmy.UniqueID();
                                                        this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.Button_Approve_Click] : Failed at CurEmailFactory.SendNow() : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    #endregion

                                    #region If the claim need to go to next approver

                                    if (this.ResultObj.Status == GonzalesClaimHeader.TypeOfClaimStatus.Escalated)
                                    {
                                        SystemUser Receiver = CurUserManager.GetUserByInternalID(this.ResultObj.NextApprover.InternalID);

                                        if (Receiver != null && Receiver.EmailID.ToLower().CompareTo("brian.king") != 0)
                                        {
                                            using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimEscalated, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                                            {
                                                MailContent = CurMailGenerator.GeneratePendingForAuthorizerClaimForAuthorizer(
                                                    Claimant.DisplayName,
                                                    Claimant.EmployeeID,
                                                    Claimant.EmailID,
                                                    Claimant.FromCompany.CompanyName,
                                                    this.ResultObj.ClaimID,
                                                    this.ResultObj.Reasons,
                                                    this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                                                    this.ResultObj.SubmittedOn.ToLongDateString(),
                                                    GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.ESCALATED_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + Receiver.EmailID);

                                                MailTitle = CurMailGenerator.MailTitle;
                                            }

                                            if (MailContent != null && MailContent.Length > 0 && MailTitle.Length > 0)
                                            {
                                                using (EmailFactory CurEmailFactory = new EmailFactory(
                                                    Receiver.DisplayName,
                                                    Receiver.Email,
                                                    MailTitle,
                                                    MailContent))
                                                {
                                                    if (!CurEmailFactory.SendNow())
                                                    {
                                                        string LogID = SwissArmy.UniqueID();
                                                        this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.Button_Approve_Click] : Failed at CurEmailFactory.SendNow() : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    #endregion
                                }

                                #endregion
                            }
                        }
                        // this is to monitor entire claim flow
                        this.CurLogManager.LogAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, GonzalesUserAction.ClaimApproved, this.ResultObj.Status);
                        //Added By Agnes [16th Aug, 2011]
                        int count = CurLogManager.GetClaimActionLogCountByClaimID(this.ClaimInternalID);
                        if (count == 0)
                            CurLogManager.CreateLogApproverClaimAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName, ClaimManager.GetClaimStatusInString(this.ResultObj.Status));
                        else
                            CurLogManager.UpdateLogApproverClaimAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName, ClaimManager.GetClaimStatusInString(this.ResultObj.Status), count.ToString());

                        Response.Redirect("GonzalesClaimsPendingForApproval.aspx");
                    }
                }   // CurUserManager
            }   // this.DataCollect()
        }   // this.DataValidate()      
    }
    #endregion

    #region Button_Reject_Click
    protected void Button_Reject_Click(object sender, EventArgs e)
    {
        if (this.DataValidate("reject"))
        {
            if (this.DataCollect())
            {
                this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.RejectedByApprover;
                this.ResultObj.LastUpdatedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                this.ResultObj.LastUpdatedOn = DateTime.Now;

                if (DataSave())
                {
                    //Added by Agnes - Hard coded for Brian.King to disabled the Email.
                    if (this.ResultObj.ClaimedBy.EmailID.ToLower().CompareTo("brian.king") != 0)
                    {
                        #region Send email

                        if (GonzalesGeneralVariables.EmailActive)
                        {
                            string MailContent = "", MailTitle = "";
                            SystemUser Receiver = null;
                            SystemUser Approver = null;

                            #region Send a mail to claimant

                            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                            {
                                Receiver = CurUserManager.GetUserByInternalID(this.ResultObj.ClaimedBy.InternalID);
                            }

                            if (Receiver != null && Receiver.EmailID.ToLower().CompareTo("brian.king") != 0)
                            {
                                using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimRejected, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                                {
                                    MailContent = CurMailGenerator.GenerateRejectedClaimForClaimant(
                                        Receiver.DisplayName,
                                        Receiver.EmployeeID,
                                        Receiver.EmailID,
                                        Receiver.FromCompany.CompanyName,
                                        this.ResultObj.ClaimID,
                                        this.ResultObj.Reasons,
                                        this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                                        ClaimManager.GetClaimStatusInString(this.ResultObj.Status) + " - " + this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName,
                                        GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.REJECTED_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + Receiver.EmailID);

                                    MailTitle = CurMailGenerator.MailTitle;
                                }

                                if (MailContent != null && MailContent.Length > 0 && MailTitle.Length > 0)
                                {
                                    using (EmailFactory CurEmailFactory = new EmailFactory(
                                        Receiver.DisplayName,
                                        Receiver.Email,
                                        MailTitle,
                                        MailContent))
                                    {
                                        if (!CurEmailFactory.SendNow())
                                        {
                                            string LogID = SwissArmy.UniqueID();
                                            this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.Button_Reject_Click] : Failed at CurEmailFactory.SendNow() : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                        }
                                    }
                                }
                            }

                            #endregion

                            #region Send mails back to previous approver

                            LogsCollection ActionLogCollection = null;
                            ActionLogCollection = this.CurLogManager.GetActionLogByClaimID(this.ClaimInternalID);

                            if (ActionLogCollection != null)
                            {
                                for (int x = 0; x < ActionLogCollection.Count; x++)
                                {
                                    ActionLogItem CurLogItem = (ActionLogItem)ActionLogCollection[x];

                                    // only pick those approved and authorized
                                    if (CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.Approved ||
                                        CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.Escalated ||
                                        CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.Authorized ||
                                        CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.PendingForAuthorize ||
                                        CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.PendingForFinanceVerification)
                                    {
                                        using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                                        {
                                            Approver = CurUserManager.GetUserByInternalID(CurLogItem.LoggedBy.InternalID);

                                            if (Approver != null && Approver.EmailID.ToLower().CompareTo("brian.king") != 0)
                                            {
                                                using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimRejectedNotifyApprover, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                                                {
                                                    MailContent = CurMailGenerator.GenerateRejectedClaimForPreviousApprover(
                                                        Receiver.DisplayName,
                                                        Receiver.EmployeeID,
                                                        Receiver.EmailID,
                                                        Receiver.FromCompany.CompanyName,
                                                        this.ResultObj.ClaimID,
                                                        this.ResultObj.Reasons,
                                                        this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                                                        ClaimManager.GetClaimStatusInString(this.ResultObj.Status) + " - " + Approver.DisplayName,
                                                        GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.REJECTEDNOTIFYAPPR_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + Receiver.EmailID,
                                                        CurLogItem.LogDate.ToLongDateString());

                                                    MailTitle = CurMailGenerator.MailTitle;
                                                }

                                                if (MailContent != null && MailContent.Length > 0 && MailTitle.Length > 0)
                                                {
                                                    using (EmailFactory CurEmailFactory = new EmailFactory(
                                                        Approver.DisplayName,
                                                        Approver.Email,
                                                        MailTitle,
                                                        MailContent))
                                                    {
                                                        if (!CurEmailFactory.SendNow())
                                                        {
                                                            string LogID = SwissArmy.UniqueID();
                                                            this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.Button_Reject_Click] : Failed at CurEmailFactory.SendNow() : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                string LogID = SwissArmy.UniqueID();
                                                this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.Button_Reject_Click] : Failed at CurUserManager.GetUserByInternalID('" + CurLogItem.LoggedBy.InternalID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                            }   // if receiver != null
                                        } // user manager
                                    }


                                }
                            }

                            #endregion
                        }

                        #endregion
                    }

                // this is to monitor entire claim flow
                this.CurLogManager.LogAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, GonzalesUserAction.ClaimRejectedByApprover, this.ResultObj.Status);

                //Added By Agnes [16th Aug, 2011]
                int count = CurLogManager.GetClaimActionLogCountByClaimID(this.ClaimInternalID);
                if (count == 0)
                    CurLogManager.CreateLogApproverClaimAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName, ClaimManager.GetClaimStatusInString(this.ResultObj.Status));
                else
                    CurLogManager.UpdateLogApproverClaimAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName, ClaimManager.GetClaimStatusInString(this.ResultObj.Status), count.ToString());

                Response.Redirect("GonzalesClaimsPendingForApproval.aspx");
            }

            }
        }  
    }
    #endregion 

    #region DropDownList_SortBy_SelectedIndexChanged
    protected void DropDownList_SortBy_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.ResultObj != null)
        {
            if (this.DropDownList_SortBy.SelectedIndex == 0)
            {
                // original order

                for (int x = (this.Table_ClaimDetailGrid.Rows.Count - 1); x > 1; x--)
                {
                    for (int y = 1; y < x; y++)
                    {
                        int Order1 = Int32.Parse(((HiddenField)this.Table_ClaimDetailGrid.Rows[y].Cells[18].Controls[1]).Value);
                        int Order2 = Int32.Parse(((HiddenField)this.Table_ClaimDetailGrid.Rows[y + 1].Cells[18].Controls[1]).Value);

                        if (Order1 > Order2)
                        {
                            TableRow Tmp1 = this.Table_ClaimDetailGrid.Rows[y];

                            this.Table_ClaimDetailGrid.Rows.RemoveAt(y);
                            this.Table_ClaimDetailGrid.Rows.AddAt(y + 1, Tmp1);
                        }
                    }
                }
            }
            else if (this.DropDownList_SortBy.SelectedIndex == 1)
            {
                // expense detail

                for (int x = (this.Table_ClaimDetailGrid.Rows.Count - 1); x > 1; x--)
                {
                    for (int y = 1; y < x; y++)
                    {
                        if (this.Table_ClaimDetailGrid.Rows[y].Cells[1].Text.CompareTo(this.Table_ClaimDetailGrid.Rows[y + 1].Cells[1].Text) > 0)
                        {
                            TableRow Tmp1 = this.Table_ClaimDetailGrid.Rows[y];

                            this.Table_ClaimDetailGrid.Rows.RemoveAt(y);
                            this.Table_ClaimDetailGrid.Rows.AddAt(y + 1, Tmp1);
                        }
                    }
                }
            }
            else if (this.DropDownList_SortBy.SelectedIndex == 2)
            {
                // claim date

                for (int x = (this.Table_ClaimDetailGrid.Rows.Count - 1); x > 1; x--)
                {
                    for (int y = 1; y < x; y++)
                    {
                        DateTime DateTime1 = SwissArmy.DateConvert(this.Table_ClaimDetailGrid.Rows[y].Cells[6].Text, this.CurrentPrivateSession.DateFormatInUse);
                        DateTime DateTime2 = SwissArmy.DateConvert(this.Table_ClaimDetailGrid.Rows[y + 1].Cells[6].Text, this.CurrentPrivateSession.DateFormatInUse);

                        if (DateTime1 > DateTime2)
                        {
                            TableRow Tmp1 = this.Table_ClaimDetailGrid.Rows[y];

                            this.Table_ClaimDetailGrid.Rows.RemoveAt(y);
                            this.Table_ClaimDetailGrid.Rows.AddAt(y + 1, Tmp1);
                        }
                    }
                }
            }
        }

        // re-validate again
        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            this.Table_ClaimDetailGrid.Rows[x].Cells[0].Text = x.ToString();
            this.Table_ClaimDetailGrid.Rows[x].Cells[17].Controls[0].Visible = false;
        }

        this.PolicyEnvironmentSetup();  // start to do policy setup

    }
    #endregion

    #region ImageButton_Cancel_Click
    protected void ImageButton_Cancel_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("GonzalesClaimsPendingForApproval.aspx");
    }

    #endregion


    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {        
        //this.Label_TotalAmount.Text += " (" + this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency.InternalID + ")";
        this.Label_TotalLocalAmount.Text = " 0";
        //this.Button_Reject.Attributes["onclick"] = "return RejectValidation();";

        this.Table_ChequeInfo.Visible = false; // by default
        this.ClaimHavingCreditCard = false; // by default

        // file upload
        this.Button_FileManager.Attributes["onclick"] = "ShowModal('FileManager', '', 'id=" + this.ClaimInternalID + "&NoEdit=1'); return false;";

        // send mail
        this.ImageButton_Mail.Attributes["onclick"] = "document.location = 'mailto:victortail@hotmail.com?subject=abc'";

        // printer friendly
        this.Button_PrinterFriendly.Attributes["onclick"] = "var windetail = window.open('GonzalesViewClaim.aspx?id=" + this.ClaimInternalID + "','','scrollbars=yes,width=800,height=600'); return false;";
        this.Button_PrinterFriendlyNameList.Attributes["onclick"] = "var windetail = window.open('GonzalesViewClaimNameList.aspx?id=" + this.ClaimInternalID + "','','scrollbars=yes,width=800,height=600'); return false;";
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_Remarks.Text = CurLanguageFactory.DisplayValue("Remarks");

                this.Label_EmployeeName.Text = CurLanguageFactory.DisplayValue("EmployeeName") + ":";
                this.Label_Category.Text = CurLanguageFactory.DisplayValue("Category") + ":";
                this.Label_EmployeeNo.Text = CurLanguageFactory.DisplayValue("EmployeeNo") + ":";
                this.Label_ClaimNum.Text = CurLanguageFactory.DisplayValue("ClaimID") + ":";
                this.Label_Purpose.Text = CurLanguageFactory.DisplayValue("Purpose") + ":";
                this.Label_CreationDate.Text = CurLanguageFactory.DisplayValue("CreationDate") + ":";
                this.Label_SubmissionDate.Text = CurLanguageFactory.DisplayValue("SubmissionDate") + ":";
                this.Label_claimPeriod.Text = CurLanguageFactory.DisplayValue("ClaimPeriod") + ":";
                this.Label_ProfitCenter.Text = CurLanguageFactory.DisplayValue("ProfitCenter") + ":";
                this.Label_TotalAmount.Text = CurLanguageFactory.DisplayValue("TotalAmount");
                this.Label_TotalAmountLessPaid.Text = CurLanguageFactory.DisplayValue("TotalAmountLessPaid");
                this.Label_OwningEmployee.Text = CurLanguageFactory.DisplayValue("OwningEmployee");
                this.Label_ChequeNo.Text = CurLanguageFactory.DisplayValue("ChequeNo");
                this.Label_IssuedBank.Text = CurLanguageFactory.DisplayValue("IssuedBank");

                this.Button_Approve.Text = CurLanguageFactory.DisplayValue("ButtonApprove");
                this.Button_Reject.Text = CurLanguageFactory.DisplayValue("ButtonReject");
                this.Button_FileManager.Text = CurLanguageFactory.DisplayValue("FileManager");
                this.Button_PrinterFriendly.Text = CurLanguageFactory.DisplayValue("PrinterFriendly");
                this.Button_PrinterFriendlyNameList.Text = CurLanguageFactory.DisplayValue("PrinterFriendlyNameList");


                this.ItemExpenseDetail = CurLanguageFactory.DisplayValue("ItemExpenseDetail");
                this.ItemRemarks = CurLanguageFactory.DisplayValue("ItemRemarks");
                this.ItemDate = CurLanguageFactory.DisplayValue("ItemClaimedDate");
                this.ItemDateEnd = CurLanguageFactory.DisplayValue("ItemClaimedDateEnd");
                this.ItemLocation = CurLanguageFactory.DisplayValue("ItemLocation");
                this.ItemClaimed = CurLanguageFactory.DisplayValue("ItemClaimedAmount");
                this.ItemTax = CurLanguageFactory.DisplayValue("ItemTax");
                this.ItemExCurrency = CurLanguageFactory.DisplayValue("ItemExCurrency");
                this.ItemExRate = CurLanguageFactory.DisplayValue("ItemExRate");
                this.ItemLocalAmount = CurLanguageFactory.DisplayValue("ItemLocalAmount");
                this.ItemTooltipsReceipt = CurLanguageFactory.DisplayValue("ItemTooltipsReceipt");
                this.ItemProjectID = CurLanguageFactory.DisplayValue("ItemProjectID");
                this.ItemChargeToProfitCenter = CurLanguageFactory.DisplayValue("ItemChargeToProfitCenter");
                this.ItemChargeToEmployeeID = CurLanguageFactory.DisplayValue("ItemChargeToEmployeeID");
                this.ItemDetail = CurLanguageFactory.DisplayValue("ItemDetail");
                this.ItemApprove = CurLanguageFactory.DisplayValue("ItemApprove");
                this.ItemTooltipApproverRemarks = CurLanguageFactory.DisplayValue("ItemTooltipApproverRemarks");
                this.CreditCardDetails =CurLanguageFactory.DisplayValue("CreditCardDetails");
                this.ReceiptNo = CurLanguageFactory.DisplayValue("ReceiptNo");

                this.AltNoDetail = CurLanguageFactory.DisplayValue("AltNoDetail");

                this.Button_Approve.Attributes["onclick"] = "return confirm('" + CurLanguageFactory.DisplayValue("ApproveConfirmation") + "');";
                this.Button_Reject.Attributes["onclick"] = "return confirm('" + CurLanguageFactory.DisplayValue("RejectConfirmation") + "');";
                //this.Button_Reject.Attributes["onclick"] = "return RejectValidation('" + CurLanguageFactory.DisplayValue("RejectConfirmation") + "');";

                // order by
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("OriginalOrder"), ""));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ItemExpenseDetail"), "ExpenseDetail"));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ItemClaimedDate"), "ClaimDate"));

                this.ItemRejectAlert = CurLanguageFactory.DisplayValue("ItemRejectAlert");
                this.ItemRejectWarning = CurLanguageFactory.DisplayValue("ItemRejectWarning");
                this.UnexpectedMesage = CurLanguageFactory.DisplayValue("UnexpectedMessage");
                this.ItemRejectMessage = CurLanguageFactory.DisplayValue("ItemRejectMessage");
                this.ApproveWarning = CurLanguageFactory.DisplayValue("ApproveWarning");
                this.ApproveWarning2 = CurLanguageFactory.DisplayValue("ApproveWarning2");


            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesClaimsPendingForApprovalDetail.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region BuiltTable
    protected void BuiltTable()
    {
        // add all the table header
        TableRow HeaderRow = new TableRow();

        for (int x = 0; x < this.TotalColumns; x++)
        {
            HeaderRow.Cells.Add(new TableCell());
            HeaderRow.Cells[x].CssClass = "GridViewHeader";
        }

        HeaderRow.Cells[0].Text = "No.";
        HeaderRow.Cells[1].Text = this.ItemExpenseDetail; HeaderRow.Cells[1].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[2].Text = "";
        HeaderRow.Cells[3].Text = "";
        HeaderRow.Cells[4].Text = this.ItemLocation; HeaderRow.Cells[4].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[5].Text = this.ReceiptNo; HeaderRow.Cells[5].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[6].Text = this.ItemDate; HeaderRow.Cells[6].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[7].Text = this.CreditCardDetails; HeaderRow.Cells[7].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[8].Text = this.ItemRemarks; HeaderRow.Cells[8].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[9].Text = this.ItemClaimed; HeaderRow.Cells[9].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[10].Text = this.ItemTax; HeaderRow.Cells[10].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[11].Text = this.ItemExCurrency; HeaderRow.Cells[11].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[12].Text = this.ItemExRate; HeaderRow.Cells[12].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[13].Text = this.ItemLocalAmount; HeaderRow.Cells[13].HorizontalAlign = HorizontalAlign.Center;        
        HeaderRow.Cells[14].Text = "R"; HeaderRow.Cells[14].HorizontalAlign = HorizontalAlign.Center; HeaderRow.Cells[14].ToolTip = this.ItemTooltipsReceipt;
        HeaderRow.Cells[15].Text = this.ItemProjectID; HeaderRow.Cells[15].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[16].Text = "D"; HeaderRow.Cells[16].HorizontalAlign = HorizontalAlign.Center; HeaderRow.Cells[16].ToolTip = this.ItemDetail;
        HeaderRow.Cells[17].Text = "";
        
        // image for approve
        //Image Image_Approve = new Image();
        //Image_Approve.ImageUrl = GonzalesImages.Icon_Approve;
        //Image_Approve.ToolTip = this.ItemTooltipApproverRemarks;
        //HeaderRow.Cells[18].Controls.Add(Image_Approve);
        //HeaderRow.Cells[18].HorizontalAlign = HorizontalAlign.Center;

        //frank change imange to checkbox
        CheckBox ckApprove = new CheckBox();
        ckApprove.ID = "checkall";
        ckApprove.AutoPostBack = true;
        HeaderRow.Cells[18].Controls.Add(ckApprove);
        HeaderRow.Cells[18].HorizontalAlign = HorizontalAlign.Center;
        ckApprove.CheckedChanged += new EventHandler(ckApprove_CheckedChanged);

        HeaderRow.Cells[19].Text = "Approver Remarks"; HeaderRow.Cells[19].HorizontalAlign = HorizontalAlign.Center;

        this.Table_ClaimDetailGrid.Rows.Add(HeaderRow);


    }
    void ckApprove_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkAll = (CheckBox)Table_ClaimDetailGrid.FindControl("checkall");
        bool chkFlag = false;
        if (chkAll.Checked) chkFlag = true;
        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            CheckBox CheckBoxApprove = (CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0];
            CheckBoxApprove.Checked = chkFlag;
        }

        //foreach (GridViewRow dr in Table_ClaimDetailGrid.Rows)
        //{
        //    CheckBox chk = (CheckBox)dr.Cells[0].FindControl("ckApprove");
        //    chk.Checked = chkFlag;
        //}
    }
    #endregion

    #region BuiltRow
    protected void BuiltRow(int RowIndex, GonzalesClaimItem CurrentClaimItem)
    {
        TableRow ItemRow = new TableRow();
        ItemRow.ID = CurrentClaimItem.InternalID;

        int CellCounter = 0;

        for (int x = 0; x < this.TotalColumns; x++)
        {
            ItemRow.Cells.Add(new TableCell());
            ItemRow.Cells[x].CssClass = "GridViewItem";
        }

        #region 0. No
        
        ItemRow.Cells[CellCounter].Text = RowIndex.ToString();
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
    
        #endregion;

        #region 1. Expense Detail / Claim Type

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.ClaimType.DisplayName;        

        #endregion

        #region 2. Detail Type

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = (CurrentClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard) ? "<img src='" + GonzalesImages.Icon_CreditCard + "'>" : "";
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 3. Is Personal

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = (CurrentClaimItem.IsPersonnal) ? "<img src='" + GonzalesImages.Icon_Personal + "'>" : "";
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 4. Country

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.Country.DisplayName;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 5. City

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.City;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 6. Date

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = SwissArmy.DateConvert(CurrentClaimItem.ClaimDate, this.CurrentPrivateSession.DateFormatInUse, "/");
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 7. Description

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.Description;
        ItemRow.Cells[CellCounter].ToolTip = CurrentClaimItem.Description;   

        #endregion

        #region 8. Remarks

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.Remarks;
        ItemRow.Cells[CellCounter].ToolTip = CurrentClaimItem.Remarks;

        #endregion

        #region 9. Claimed Amount

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.ClaimedAmount.ToString(GonzalesGeneralVariables.CurrencyFormat);
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 10. TAX / GST

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.Tax.ToString();
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 11. Exchange Currency

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.ExchangeCurrency.DisplayName;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 12. Exchange Rate

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = Convert.ToDecimal(CurrentClaimItem.ExchangeRate).ToString();
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        try
        {
            if (Convert.ToDecimal(CurrentClaimItem.ExchangeRate) > CurrentClaimItem.ActualExchangeRate)
            {
                if (((((Convert.ToDecimal(CurrentClaimItem.ExchangeRate) - CurrentClaimItem.ActualExchangeRate) / (CurrentClaimItem.ActualExchangeRate == 0 ? 1 : CurrentClaimItem.ActualExchangeRate)) * 100) > 5))
                {
                    // different more than 5%
                    StringBuilder MessageBuilder = new StringBuilder();
                    MessageBuilder.AppendLine("Exchange Rate diffrence more than 5%\n");
                    MessageBuilder.AppendLine("Actual Exchange Rate: " + Convert.ToDecimal(CurrentClaimItem.ActualExchangeRate));

                    HyperLink AlertIndicator = new HyperLink();
                    AlertIndicator.Text = Convert.ToDecimal(CurrentClaimItem.ExchangeRate).ToString();
                    AlertIndicator.CssClass = "GridViewAlertIndicator";
                    AlertIndicator.ToolTip = MessageBuilder.ToString();
                    AlertIndicator.NavigateUrl = "#";
                    AlertIndicator.Attributes["onclick"] = "alert(this.title);";

                    ItemRow.Cells[CellCounter].Controls.Add(AlertIndicator);
                }
            }
        }
        catch (Exception ex)
        {
            string LogID = SwissArmy.UniqueID();
            this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.BuiltRow] : Exception at 16. Exceed Limit Indicator : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            this.ShowErrorMessage("Error! " + LogID);

        }

        #endregion

        #region 13. Local Amount

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.AmountOut.ToString(GonzalesGeneralVariables.CurrencyFormat);
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 14. Having Receipts

        Image ImageHavingReceipts = new Image();
        ImageHavingReceipts.ImageUrl = (CurrentClaimItem.HavingReceipts)?GonzalesImages.Icon_Checked:GonzalesImages.Icon_Crossed;

        HiddenField HiddenFieldHavingReceipts = new HiddenField();
        HiddenFieldHavingReceipts.Value = (CurrentClaimItem.HavingReceipts) ? "1" : "0";
        
        CellCounter++;
        ItemRow.Cells[CellCounter].Controls.Add(ImageHavingReceipts);
        ItemRow.Cells[CellCounter].Controls.Add(HiddenFieldHavingReceipts);
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 15. Project ID

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.ProjectID;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 16. Popout Detail

        


            HiddenField HiddenPopOut = new HiddenField();
            HiddenPopOut.ID = CurrentClaimItem.InternalID + "_HiddenPopOut";
            HiddenPopOut.Value = "0"; // default

            HiddenField HiddenAlreadySeen = new HiddenField();
            HiddenAlreadySeen.ID = CurrentClaimItem.InternalID + "_HiddenAlreadySeen";
            HiddenAlreadySeen.Value = "0";

            HiddenField HiddenGLCode = new HiddenField();
            HiddenGLCode.ID = CurrentClaimItem.InternalID + "_HiddenGLCode";
            HiddenGLCode.Value = CurrentClaimItem.ClaimType.GLCode;

            ImageButton ImageButtonDetail = new ImageButton();
            ImageButtonDetail.ID = CurrentClaimItem.InternalID + "_ImageButtonDetail";
            ImageButtonDetail.ImageUrl = GonzalesImages.Icon_Detail;
            ImageButtonDetail.Attributes["onclick"] = "ShowSpecialPopOut('" + CurrentClaimItem.ClaimType.GLCode + "', null, 'NoEdit=1&id=" + this.ClaimInternalID + "&did=" + CurrentClaimItem.InternalID + "&remarks=" + CurrentClaimItem.Remarks.Replace("'", "#") + "'); document.getElementById('" + CurrentClaimItem.InternalID + "_HiddenAlreadySeen').value = 1;return false;";

            CellCounter++;
            ItemRow.Cells[CellCounter].Controls.Add(HiddenPopOut);
            ItemRow.Cells[CellCounter].Controls.Add(ImageButtonDetail);
            ItemRow.Cells[CellCounter].Controls.Add(HiddenAlreadySeen);
            ItemRow.Cells[CellCounter].Controls.Add(HiddenGLCode);
            ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        

        #endregion

        #region 17. Exceed Limit Indicator

        CellCounter++;

        Image Image_WarningIndicator = new Image();
        Image_WarningIndicator.Visible = false;
        Image_WarningIndicator.ID = ItemRow.ID + "_Image_WarningIndicator";

        ItemRow.Cells[CellCounter].Controls.Add(Image_WarningIndicator);
        ItemRow.Cells[CellCounter].ID = ItemRow.ID + "_LimitValidationColumn";
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 18. Approval

        CheckBox CheckBoxApproverState = new CheckBox();
        CheckBoxApproverState.ID = ItemRow.ID + "_ApproverState";
       // CheckBoxApproverState.Attributes["onclick"] = "document.getElementById('" + ItemRow.ID + "_ApproverRemarks').value = (this.checked)?'':document.getElementById('" + ItemRow.ID + "_ApproverRemarks').value;";        

        HiddenField HiddenFieldOrder = new HiddenField();
        HiddenFieldOrder.ID = ItemRow.ID + "_Order";
        HiddenFieldOrder.Value = CurrentClaimItem.Order.ToString();

        CellCounter++;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        ItemRow.Cells[CellCounter].Controls.Add(CheckBoxApproverState);
        ItemRow.Cells[CellCounter].Controls.Add(HiddenFieldOrder);        

        #endregion

        #region 19. Remarks

        TextBox TextBoxApproverRemarks = new TextBox();
        TextBoxApproverRemarks.ID = ItemRow.ID + "_ApproverRemarks";
        TextBoxApproverRemarks.CssClass = "DetailGridTextBox";
        TextBoxApproverRemarks.Width = Unit.Percentage(90);
        TextBoxApproverRemarks.Attributes["OnChange"] = "this.title = this.value;";

        CellCounter++;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        ItemRow.Cells[CellCounter].Controls.Add(TextBoxApproverRemarks);

        #endregion 

        //Added by Agnes for Total Personal Expenses
        if (CurrentClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard && CurrentClaimItem.IsPersonnal)
            TotalPersonalExpenses -= CurrentClaimItem.AmountOut;

        // final
        this.Table_ClaimDetailGrid.Rows.Add(ItemRow);
    }

    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
    }
    #endregion    

    #endregion

    #region Data Operation

    #region LoadData

    public void LoadData()
    {
        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {
            this.ResultObj = CurClaimManager.GetClaimByInternalID(this.ClaimInternalID);

            if ((this.ResultObj.Status == GonzalesClaimHeader.TypeOfClaimStatus.Submitted || this.ResultObj.Status == GonzalesClaimHeader.TypeOfClaimStatus.Escalated) && this.ResultObj.NextApprover.InternalID.CompareTo(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID) == 0)
            {

                if (this.ResultObj != null)
                {
                    this.ResultObj.ClaimDetails = CurClaimManager.GetClaimItemsByClaimHeaderInLang(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage);

                    //Added By Agnes[09 April 2009] - For Enhancement to enabled/disabled the PrinterFriendlyNameList
                    //if (this.ResultObj.Category == CategoryOfClaim.Entertainment)
                    //    this.Button_PrinterFriendlyNameList.Visible = true;

                    if (this.ResultObj.ClaimDetails == null)
                    {
                        string LogID = SwissArmy.UniqueID();
                        this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.LoadData] : Failed at CurClaimManager.GetClaimItemsByClaimHeaderInLang('" + this.ClaimInternalID + "') : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                    }
                }
                else
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.LoadData] : Failed at CurClaimManager.GetClaimByInternalID('" + this.ClaimInternalID + "') : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                }
            }
            else
            {
                // wrong status, could be already change, no longer valid
                Server.Transfer("GonzalesViewClaim.aspx?id=" + this.ClaimInternalID);
            }
        }

        #region Supporting Documents

        using (FileManager CurFileManager = new FileManager(this.CurrentPrivateSession))
        {
            SupportingDocuments ListOfDocs = CurFileManager.GetFilesByClaimID(this.ClaimInternalID);
            if (ListOfDocs != null)
            {
                if (this.Button_FileManager.Text.IndexOf("(") <= 0)
                {
                    this.Button_FileManager.Text += " (" + ListOfDocs.Count + ")";
                }
            }
            else
            {
                if (this.Button_FileManager.Text.IndexOf("(") <= 0)
                {
                    this.Button_FileManager.Text += " (0)";
                }

                string ErrorID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(ErrorID, "[GonzalesMyClaimDetail.LoadData] : Failed at CurFileManager.GetFilesByClaimID(" + this.ClaimInternalID + ") : " + CurFileManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            }
        }

        #endregion

    }

    #endregion    

    #region FillInData

    protected void FillInData()
    {
        if (this.ResultObj != null)
        {
            this.LabelValue_ClaimNo.Text = this.ResultObj.ClaimID;
            this.LabelValue_CreationDate.Text = SwissArmy.DateConvert(this.ResultObj.CreatedOn, this.CurrentPrivateSession.DateFormatInUse, "/");
            this.LabelValue_SubmissionDate.Text = SwissArmy.DateConvert(this.ResultObj.SubmittedOn, this.CurrentPrivateSession.DateFormatInUse, "/");
            this.LabelValue_EmployeeName.Text = this.ResultObj.ClaimedBy.DisplayName + " (" + this.ResultObj.ClaimedBy.EmailID + ")";
            this.LabelValue_EmployeeNo.Text = this.ResultObj.ClaimedBy.EmployeeID;
            this.LabelValue_Purpose.Text = this.ResultObj.Reasons;
            this.LabelValue_ProfitCenter.Text = this.ResultObj.ClaimedBy.CostCenter;
            this.LabelValue_Category.Text = ClaimManager.GetClaimCategoryInString(this.ResultObj.Category);
            if(this.ResultObj.ProjectedOn != DateTime.MinValue)
                this.LabelValue_ClaimPeriod.Text = this.ResultObj.ProjectedOn.Year.ToString() + " - " + this.ResultObj.ProjectedOn.Month.ToString();

            this.Label_TotalAmount.Text += " (" + this.ResultObj.LocalCurrency.InternalID + ")";
            this.Label_TotalLocalAmount.Text = this.ResultObj.TotalClaimedAmount.ToString(GonzalesGeneralVariables.CurrencyFormat);
            this.Label_TotalAmountAlreadyPaid.Text = this.ResultObj.TotalLocalAmountAlreadyPaid.ToString(GonzalesGeneralVariables.CurrencyFormat);
            this.Label_Owning.Text = this.ResultObj.TotalLocalActualAmountLeft.ToString(GonzalesGeneralVariables.CurrencyFormat);

            if (this.ResultObj.ChequeNo.Length > 0)
            {
                this.Table_ChequeInfo.Visible = true;
                this.LabelValue_ChequeNo.Text = this.ResultObj.ChequeNo;
                this.LabelValue_IssuedBank.Text = this.ResultObj.ChequeIssuesBank;
            }

            this.ImageButton_Mail.ToolTip = "Send an email to " + this.ResultObj.ClaimedBy.DisplayName;
            this.ImageButton_Mail.Attributes["onclick"] = "document.location = 'mailto:" + this.ResultObj.ClaimedBy.Email + "?subject=[" + GonzalesGeneralVariables.WebsiteName + "] Enquiry: " + this.ResultObj.ClaimID + "'; return false;";
        }
    }

    #endregion

    #region PolicyEnvironmentSetup

    protected void PolicyEnvironmentSetup()
    {
        if (this.ResultObj != null)
        {
            using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
            {
                ClaimTypeLimitPolicies PolicyCollections = null;
                if ((PolicyCollections = CurClaimManager.GetClaimItemLimitPolicies((SystemUser)this.ResultObj.ClaimedBy, this.ResultObj.InternalID)) != null)
                {
                    this.DataValidateByPolicy(PolicyCollections);
                }
                else
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.PolicyEnvironmentSetup] : Failed at CurClaimManager.GetClaimItemLimitPolicies() : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }
        }
    }

    #endregion

    #region DataValidateByPolicy

    #region Not Using
    public void DataValidateByPolicyX(ClaimTypeLimitPolicies LimitPolicy)
    {       
        // compare by policy
        // this policy will go by every single row
        for (int x = 0; x < LimitPolicy.Count; x++)
        {
            bool IsExceedLimit = false;
            string ClaimDetailRemarks = "";

            // get the description, to check if this is a entertainment
            for (int y = 1; y < this.Table_ClaimDetailGrid.Rows.Count; y++)
            {
                if (this.Table_ClaimDetailGrid.Rows[y].UniqueID.CompareTo(LimitPolicy[x].ClaimDetalID) == 0)
                {
                    ClaimDetailRemarks = this.Table_ClaimDetailGrid.Rows[y].Cells[8].Text;
                    break;
                }
            }

            // check the currency if it is the same
            // if not same, muz convert the currency first
            if (LimitPolicy[x].LimitCurrency.InternalID.CompareTo(LimitPolicy[x].LocalCurrency.InternalID) == 0)
            {
                // same currency                
                if (ClaimDetailRemarks.IndexOf("[ENT]") == 0)
                {
                    string[] RemarksArray = SwissArmy.StringSplit(ClaimDetailRemarks, ",");
                    int TotaParticipants = Convert.ToInt32(RemarksArray[1]);
                    decimal TotalCostPerHead = (LimitPolicy[x].TotalClaimedInPeriod / TotaParticipants);

                    IsExceedLimit = (TotalCostPerHead > LimitPolicy[x].LimitAmount);

                }
                else
                {
                    IsExceedLimit = (LimitPolicy[x].TotalClaimedInPeriod > LimitPolicy[x].LimitAmount);
                }
            }
            else
            {
                if (ClaimDetailRemarks.IndexOf("[ENT]") == 0)
                {
                    string[] RemarksArray = SwissArmy.StringSplit(ClaimDetailRemarks, ",");
                    int TotaParticipants = Convert.ToInt32(RemarksArray[1]);
                    decimal TotalCostPerHead = (LimitPolicy[x].TotalClaimedInPeriod / TotaParticipants);

                    IsExceedLimit = ((TotalCostPerHead * LimitPolicy[x].ExRateFigure) > LimitPolicy[x].LimitAmount);

                }
                else
                {
                    IsExceedLimit = ((LimitPolicy[x].TotalClaimedInPeriod * LimitPolicy[x].ExRateFigure) > LimitPolicy[x].LimitAmount);
                }
            }

            // exceed limit, muz do something
            if (IsExceedLimit)
            {
                for (int y = 1; y < this.Table_ClaimDetailGrid.Rows.Count; y++)
                {
                    if (this.Table_ClaimDetailGrid.Rows[y].ID.CompareTo(LimitPolicy[x].ClaimDetalID) == 0)
                    {
                        
                            StringBuilder MessageBuilder = new StringBuilder("");
                            MessageBuilder.Append("Alert: Exceed Limit\n");
                            MessageBuilder.Append("Duration: " + ClaimManager.GetClaimTypeLimitDurationInString(LimitPolicy[x].Duration) + "\n");
                            MessageBuilder.Append("Approved Limit: " + LimitPolicy[x].LimitCurrency.DisplayName + " " + LimitPolicy[x].LimitAmount + "\n");

                            Image ImageExceedLimit = (Image)this.Table_ClaimDetailGrid.Rows[y].Cells[17].Controls[0];
                            ImageExceedLimit.ImageUrl = GonzalesImages.Icon_Warning;
                            ImageExceedLimit.Visible = true;
                            ImageExceedLimit.ToolTip = MessageBuilder.ToString();
                            ImageExceedLimit.Attributes["onclick"] = "alert(this.title)";

                           

                        

                        break;
                    }
                }
            } // if exceed limit
        }

        // check the checkbox that no need to check
        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            if (this.Table_ClaimDetailGrid.Rows[x].Cells[17].Controls.Count == 0)
            {
                ((CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0]).Checked = true;
            }
        }
    }
    #endregion

    public void DataValidateByPolicy(ClaimTypeLimitPolicies LimitPolicy)
    {
        // compare by policy
        // this policy will go by every single row
        for (int x = 0; x < LimitPolicy.Count; x++)
        {
            bool IsExceedLimit = false;
            string ClaimDetailRemarks = "";

            // get the description, to check if this is a entertainment
            for (int y = 1; y < this.Table_ClaimDetailGrid.Rows.Count; y++)
            {
                if (this.Table_ClaimDetailGrid.Rows[y].UniqueID.CompareTo(LimitPolicy[x].ClaimDetalID) == 0)
                {
                    ClaimDetailRemarks = this.Table_ClaimDetailGrid.Rows[y].Cells[8].Text;
                    break;
                }
            }

            for (int y = 1; y < this.Table_ClaimDetailGrid.Rows.Count; y++)
            {
                if (this.Table_ClaimDetailGrid.Rows[y].ID.CompareTo(LimitPolicy[x].ClaimDetalID) == 0)
                {
                    
                    // check the currency if it is the same
                    // if not same, muz convert the currency first
                    if (LimitPolicy[x].LimitCurrency.InternalID.CompareTo(LimitPolicy[x].LocalCurrency.InternalID) == 0)
                    {
                        // same currency
                        if (ClaimDetailRemarks.IndexOf("[ENT]") == 0)
                        {
                            string[] RemarksArray = SwissArmy.StringSplit(ClaimDetailRemarks, ",");
                            int TotaParticipants = Convert.ToInt32(RemarksArray[1]);
                            decimal TotalCostPerHead = (LimitPolicy[x].TotalClaimedInPeriod / TotaParticipants);

                            IsExceedLimit = (TotalCostPerHead > LimitPolicy[x].LimitAmount);
                        }
                        else
                        {
                            IsExceedLimit = (LimitPolicy[x].TotalClaimedInPeriod > LimitPolicy[x].LimitAmount);
                        }
                    }
                    else
                    {
                        if (ClaimDetailRemarks.IndexOf("[ENT]") == 0)
                        {
                            string[] RemarksArray = SwissArmy.StringSplit(ClaimDetailRemarks, ",");
                            int TotaParticipants = Convert.ToInt32(RemarksArray[1]);
                            decimal TotalCostPerHead = (LimitPolicy[x].TotalClaimedInPeriod / TotaParticipants);

                            IsExceedLimit = ((TotalCostPerHead * LimitPolicy[x].ExRateFigure) > LimitPolicy[x].LimitAmount);

                        }
                        else
                        {
                            IsExceedLimit = ((LimitPolicy[x].TotalClaimedInPeriod * LimitPolicy[x].ExRateFigure) > LimitPolicy[x].LimitAmount);
                        }
                    }

                    // exceed limit, muz do something
                    if (IsExceedLimit)
                    {
                        StringBuilder MessageBuilder = new StringBuilder("");
                        MessageBuilder.Append("Alert: Exceed Limit\n");
                        MessageBuilder.Append("Duration: " + ClaimManager.GetClaimTypeLimitDurationInString(LimitPolicy[x].Duration) + "\n");
                        MessageBuilder.Append("Approved Limit: " + LimitPolicy[x].LimitCurrency.DisplayName + " " + LimitPolicy[x].LimitAmount.ToString(GonzalesGeneralVariables.CurrencyFormat) + "\n");

                        Image ImageExceedLimit = (Image)this.Table_ClaimDetailGrid.Rows[y].Cells[17].Controls[0];
                        ImageExceedLimit.ImageUrl = GonzalesImages.Icon_Warning;
                        ImageExceedLimit.Visible = true;
                        ImageExceedLimit.ToolTip = MessageBuilder.ToString();
                        ImageExceedLimit.Attributes["onclick"] = "alert(this.title)";

                        break;

                    } // if exceed limit
                }
                
            }
        }

        // check the checkbox that no need to check
        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            if (!this.Table_ClaimDetailGrid.Rows[x].Cells[17].Controls[0].Visible && ((HiddenField)this.Table_ClaimDetailGrid.Rows[x].Cells[14].Controls[1]).Value.CompareTo("1") == 0 )
            {
                ((CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0]).Checked = true;
            }
        }
    }
    #endregion

    #region DataValidate

    protected bool DataValidate(string status)
    {
        bool smooth = true;
        StringBuilder MessageBuilder = new StringBuilder("<ul>");

        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            // check approval
            CheckBox CheckBoxApproval = (CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0];
            if (status.CompareTo("approved") != 0)
            {
                //if (!CheckBoxApproval.Checked)
                //{
                //    TextBox HiddenFieldApproverRemarks = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[19].Controls[0];
                //    if (HiddenFieldApproverRemarks.Text.Length == 0)
                //    {
                //        MessageBuilder.AppendLine("<li>Please enter remarks for item #" + x + ", as this item has not been approved by you..</li>");
                //        smooth = false;
                //    }
                //}
                TextBox HiddenFieldApproverRemarks = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[19].Controls[0];
                if (HiddenFieldApproverRemarks.Text.Length > 0)
                {
                    smooth = true;
                    break;
                }
                else
                {
                    if (MessageBuilder.ToString().Length < 10)
                    {
                        MessageBuilder.AppendLine("<li>" + this.ItemRejectMessage + "</li>");
                        smooth = false;
                    }
                }
            }
            else
            {
                if (!CheckBoxApproval.Checked)
                {
                    MessageBuilder.AppendLine("<li>" + this.ApproveWarning + x + this.ApproveWarning2);
                    smooth = false;
                }
            }

            #region check pop out - no longer needed
            /*
             * 
            HiddenField HiddenFieldPopOut = (HiddenField)this.Table_ClaimDetailGrid.Rows[x].Cells[16].Controls[0];

            if (HiddenFieldPopOut.Value.CompareTo("1") == 0)
            {   // having pop out, check if already seen
                HiddenField HiddenFiledAlreadySeen = (HiddenField)this.Table_ClaimDetailGrid.Rows[x].Cells[16].Controls[2];
                if (HiddenFiledAlreadySeen.Value.CompareTo("1") != 0)
                {
                    MessageBuilder.AppendLine("<li>Please check the detailed information for item #" + x + " before approving.</li>");
                    smooth = false;
                }
            }
            
            */
            #endregion
        }

        MessageBuilder.AppendLine("</ul>");

        if (!smooth) this.ShowErrorMessage(MessageBuilder.ToString());

        return smooth;

    }

    #endregion

    #region DataCollect

    protected bool DataCollect()
    {
        bool smooth = true;

        if (this.ResultObj != null)
        {               
            // start to collect data now
            for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
            {
                for (int y = 0; y < this.ResultObj.ClaimDetails.Count; y++)
                {
                    if (this.ResultObj.ClaimDetails[y].InternalID.CompareTo(this.Table_ClaimDetailGrid.Rows[x].ID) == 0)
                    {
                        // match, do a compare now
                        CheckBox CheckBoxApproval = (CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0];                        
                        TextBox HiddenFieldApproverRemarks = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[19].Controls[0];

                        this.ResultObj.ClaimDetails[y].ApproverState = CheckBoxApproval.Checked;
                        this.ResultObj.ClaimDetails[y].ApproverRemarks = HiddenFieldApproverRemarks.Text;                                

                        break;
                    }
                }   // y
            }   // x
        }
           
        return smooth;
    }

    #endregion 

    #region DataSave

    protected bool DataSave()
    {
        bool smooth = true;

        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {
            if (!CurClaimManager.UpdateClaimByApprover(this.ResultObj))
            {
                smooth = false;

                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.DataSave] : Failed at CurClaimManager.UpdateClaimByApprover() : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage(this.UnexpectedMesage + LogID);
            }             
        }

        return smooth;
    }

    #endregion

    #region GetAuthorizer

    protected Authoriser GetAuthorizer(ref bool AuthorizedNeeded)
    {
        SystemUsers AuthorizersCollection = null;
        SystemUser Claimant = null;
        Authoriser ResultAuthorizer = null;

        #region 1. Get list of Authorizers

        using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
        {
            Claimant = CurUserManager.GetUserByInternalID(this.ResultObj.ClaimedBy.InternalID);

            if (Claimant != null)
            {
                AuthorizersCollection = CurUserManager.GetAuthorizersByEntity(Claimant.FromCompany.Entity.InternalID);

                if (AuthorizersCollection == null)
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.GetAuthorizer] : Failed at CurUserManager.GetAuthorizersByEntity('" + Claimant.FromCompany.Entity.InternalID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage("Error! " + LogID);
                }
            }
            else
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.GetAuthorizer] : Failed at CurUserManager.GetUserByInternalID('" + this.ResultObj.ClaimedBy.InternalID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage("Error! " + LogID);
            }
        }

        #endregion

        #region 2. Get simple summary of claim detail with weekly limit (Not using)

        /*
        if (AuthorizersCollection != null)
        {
            MasterBaseCollection CurrencyCollection = null;

            // diff currency, need to convert
            using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
            {
                CurrencyCollection = CurCurrencyManager.GetLatestExchangeRate(this.ResultObj.LocalCurrency);
            }

            using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
            {
                ClaimItems CurClaimItems = CurClaimManager.GetSimpleClaimItemsByClaimHeaderWithWeeklyLmit(this.ClaimInternalID, Claimant.InternalID);

                if (CurClaimItems != null)
                {
                    decimal CurrentMaxAmount = 0; // maxium amount so far

                    // get the max amount first
                    for (int x = 0; x < CurClaimItems.Count; x++)
                    {
                        GonzalesClaimItemWithWeeklyLimit CurrentItem = (GonzalesClaimItemWithWeeklyLimit)CurClaimItems[x];                        
                        CurrentMaxAmount = (CurrentItem.TotalSpentInWeek > CurrentMaxAmount) ? CurrentItem.TotalSpentInWeek : CurrentMaxAmount;
                    }

                    for (int x = 0; x < AuthorizersCollection.Count; x++)
                    {
                        Authoriser CurrentAuthorizer = (Authoriser)AuthorizersCollection[x];

                        decimal MinLimitInLocal = 0, MaxLimitInLocal = 0;

                        // convert to local currency
                        if (this.ResultObj.LocalCurrency.InternalID.CompareTo(CurrentAuthorizer.LimitCurrency.InternalID) == 0)
                        {
                            // same to local currency 
                            MinLimitInLocal = CurrentAuthorizer.MinLimit;
                            MaxLimitInLocal = CurrentAuthorizer.MaxLimit;
                        }
                        else
                        {
                            // compare with foreign currency
                            for (int y = 0; y < CurrencyCollection.Count; y++)
                            {
                                Currency CurCurrency = (Currency)CurrencyCollection[y];

                                if (CurCurrency.InternalID.CompareTo(CurrentAuthorizer.LimitCurrency.InternalID) == 0)
                                {
                                    MinLimitInLocal = CurrentAuthorizer.MinLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());
                                    MaxLimitInLocal = CurrentAuthorizer.MaxLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());
                                    break;
                                }
                            }
                        }

                        if (CurrentMaxAmount >= MinLimitInLocal &&
                            CurrentMaxAmount <= MaxLimitInLocal)
                        {
                            // found the authorizer
                            AuthorizedNeeded = true;
                            ResultAuthorizer = CurrentAuthorizer;
                            break;
                        }
                    }                    
                }
                else
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.GetAuthorizer] : Failed at CurClaimManager.GetSimpleClaimItemsByClaimHeaderWithWeeklyLmit('" + this.ClaimInternalID + "', '" + Claimant.InternalID + "') : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage("Error! " + LogID);
                }
            }
        }
        */

        #endregion

        #region 2. Check if total claim exceed the limit.

        if (AuthorizersCollection != null)
        {
            MasterBaseCollection CurrencyCollection = null;

            // diff currency, need to convert
            using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
            {
                CurrencyCollection = CurCurrencyManager.GetLatestExchangeRate(this.ResultObj.LocalCurrency);
            }

            for (int x = 0; x < AuthorizersCollection.Count; x++)
            {
                Authoriser CurrentAuthorizer = (Authoriser)AuthorizersCollection[x];

                decimal MinLimitInLocal = 0, MaxLimitInLocal = 0;

                // convert to local currency
                if (this.ResultObj.LocalCurrency.InternalID.CompareTo(CurrentAuthorizer.LimitCurrency.InternalID) == 0)
                {
                    // same to local currency 
                    MinLimitInLocal = CurrentAuthorizer.MinLimit;
                    MaxLimitInLocal = CurrentAuthorizer.MaxLimit;
                }
                else
                {
                    // compare with foreign currency
                    for (int y = 0; y < CurrencyCollection.Count; y++)
                    {
                        Currency CurCurrency = (Currency)CurrencyCollection[y];

                        if (CurCurrency.InternalID.CompareTo(CurrentAuthorizer.LimitCurrency.InternalID) == 0)
                        {
                            MinLimitInLocal = CurrentAuthorizer.MinLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());
                            MaxLimitInLocal = CurrentAuthorizer.MaxLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());
                            break;
                        }
                    }
                }

                // ready to compare now
                if (this.ResultObj.TotalClaimedAmount >= MinLimitInLocal && this.ResultObj.TotalClaimedAmount <= MaxLimitInLocal)
                {
                    // found the authorizer
                    AuthorizedNeeded = true;
                    ResultAuthorizer = CurrentAuthorizer;
                    break;
                }
            }
        }

        #endregion

        return ResultAuthorizer;


    }

    #endregion

    #region ShadowUserPolicy
    protected void ShadowUserPolicy()
    {
        if (this.CurrentPrivateSession.ShadowMode)
        {
            if (this.CurrentPrivateSession.CurrentLoggedOnUser.ReviewOnBehalfBy != null &&
                this.CurrentPrivateSession.CurrentLoggedOnUser.ReviewOnBehalfBy.InternalID.CompareTo(this.CurrentPrivateSession.ShadowUser.InternalID) == 0)
            {
                // shadow user can't do any action
                this.Button_Approve.Visible = this.Button_Reject.Visible = false;
            }

        }
    }
    #endregion

    #endregion

    #region Javascripts

    #region GeneralVariable
    public void GeneralVariable()
    {
        StringBuilder JSBuilder = new StringBuilder();
        JSBuilder.AppendLine("<script language='javascript'>");
        JSBuilder.AppendLine("var FirstTimeLoad = " + IsFirstTime + ";");
        JSBuilder.AppendLine("var ItemRejectAlert = " + this.ItemRejectAlert + ";");
        JSBuilder.AppendLine("var ItemRejectWarning = " + this.ItemRejectWarning + ";");

        JSBuilder.AppendLine("</script>");

        // done, generate on the page
        if (!this.ClientScript.IsClientScriptBlockRegistered("GeneralVariable"))
        {
            this.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "GeneralVariable", JSBuilder.ToString());
        }
    }
    #endregion

    #endregion

}
